//==============================================================================================================================================================
// Author(s): Wei Jiang
// Updated by Wei 2013/08/11
// This module will be droppped
// Class used for tcp connection
//==============================================================================================================================================================

#ifndef TCP_CONNECTION_H_
#define TCP_CONNECTION_H_

//#include "query_processor.h"

#include <cstdlib>
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include "boost/tuple/tuple.hpp"

//#include <boost/serialization/vector.hpp>



using boost::asio::ip::tcp;
using namespace std;

struct queryResults;
struct query;
struct queryResult;




class sessionForBroker: public boost::enable_shared_from_this<sessionForBroker>
{
public:
  typedef boost::shared_ptr<sessionForBroker> pointer;

  sessionForBroker(boost::asio::io_service& io_service);

  tcp::socket& socket();

  void welcome(string queryString);

  void startQueryOnThisMachineWithOneQuery(string queryString);

  void startQueryOnThisMachineWithQueriesInside();

  void startQueryOnThisMachine(vector<pair<int, string> > &queries);

  void startQueryOnThisMachine(vector<string> &queries);

  string getReturningResult();

  void addSpecificQueryToTCPSession(int number, string queryContent);

  int getQueryLogSize();

  /// Asynchronously write a data structure to the socket.
  template <typename T, typename Handler>
  void async_write(const T& t, Handler handler)
  {

    // Serialize the data first so we know how large it is.
    std::ostringstream archive_stream;
    boost::archive::text_oarchive archive(archive_stream);
    archive << t;
    outbound_data_ = archive_stream.str();


    // Format the header.
    std::ostringstream header_stream;
    header_stream << std::setw(header_length)
      << std::hex << outbound_data_.size();

    if (!header_stream || header_stream.str().size() != header_length)
    {
      cout << "something goes wrong with the function async_write(...)" << endl;
      /*
      // Something went wrong, inform the caller.
      boost::system::error_code error(boost::asio::error::invalid_argument);
      socket_.get_io_service().post(boost::bind(handler, error));
      */
      return;
    }

    outbound_header_ = header_stream.str();

    // Write the serialized data to the socket. We use "gather-write" to send
    // both the header and the data in a single write operation.
    std::vector<boost::asio::const_buffer> buffers;
    buffers.push_back(boost::asio::buffer(outbound_header_));
    buffers.push_back(boost::asio::buffer(outbound_data_));
    boost::asio::async_write(socket_, buffers, handler);

  }

  /// Asynchronously read a data structure from the socket.
  template <typename T, typename Handler>
  void async_read(T& t, Handler handler)
  {
    // Issue a read operation to read exactly the number of bytes in a header.
    void (sessionForBroker::*f)(
        const boost::system::error_code&,
        T&, boost::tuple<Handler>)
      = &sessionForBroker::handle_read_header<T, Handler>;
    boost::asio::async_read(socket_, boost::asio::buffer(inbound_header_),
        boost::bind(f,
          this, boost::asio::placeholders::error, boost::ref(t),
          boost::make_tuple(handler)));
  }

  /// Handle a completed read of a message header. The handler is passed using
  /// a tuple since boost::bind seems to have trouble binding a function object
  /// created using boost::bind as a parameter.
  template <typename T, typename Handler>
  void handle_read_header(const boost::system::error_code& e,
      T& t, boost::tuple<Handler> handler)
  {
    if (e)
    {
      boost::get<0>(handler)(e);
    }
    else
    {
      // Determine the length of the serialized data.
      std::istringstream is(std::string(inbound_header_, header_length));
      std::size_t inbound_data_size = 0;
      if (!(is >> std::hex >> inbound_data_size))
      {
        // Header doesn't seem to be valid. Inform the caller.
        boost::system::error_code error(boost::asio::error::invalid_argument);
        boost::get<0>(handler)(error);
        return;
      }

      // Start an asynchronous call to receive the data.
      inbound_data_.resize(inbound_data_size);
      void (sessionForBroker::*f)(
          const boost::system::error_code&,
          T&, boost::tuple<Handler>)
        = &sessionForBroker::handle_read_data<T, Handler>;
      boost::asio::async_read(socket_, boost::asio::buffer(inbound_data_),
        boost::bind(f, this,
          boost::asio::placeholders::error, boost::ref(t), handler));
    }
  }

  /// Handle a completed read of message data.
  template <typename T, typename Handler>
  void handle_read_data(const boost::system::error_code& e,
      T& t, boost::tuple<Handler> handler)
  {
    if (e)
    {
      boost::get<0>(handler)(e);
    }
    else
    {
      // Extract the data structure from the data just received.
      try
      {
        std::string archive_data(&inbound_data_[0], inbound_data_.size());
        std::istringstream archive_stream(archive_data);
        boost::archive::text_iarchive archive(archive_stream);
        archive >> t;
      }
      catch (std::exception& e)
      {
        // Unable to decode data.
        boost::system::error_code error(boost::asio::error::invalid_argument);
        boost::get<0>(handler)(error);
        return;
      }

      // Inform caller that data has been received ok.
      boost::get<0>(handler)(e);
    }
  }

private:


  void handle_read(const boost::system::error_code& error, size_t bytes_transferred);
  void handle_read_for_queries(const boost::system::error_code& error);

  void handle_write(const boost::system::error_code& error, size_t bytes_transferred);
  void handle_write_for_queries(const boost::system::error_code& error, size_t bytes_transferred);

  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
  char returnResult_[max_length];
  size_t bytes_transferred_;
  /// The data to be sent to each client.
  std::vector<query> queries_loaded_;
  std::vector<queryResults> queries_with_results_;




  /// The size of a fixed length header.
  enum { header_length = 8 };

  /// Holds an outbound header.
  std::string outbound_header_;

  /// Holds the outbound data.
  std::string outbound_data_;

  /// Holds an inbound header.
  char inbound_header_[header_length];

  /// Holds the inbound data.
  std::vector<char> inbound_data_;

};

class sessionOriginal
{
public:
  sessionOriginal(boost::asio::io_service& io_service);

  tcp::socket& socket();

  void start(string queryString);

private:
  void handle_read(const boost::system::error_code& error,size_t bytes_transferred);

  void handle_write(const boost::system::error_code& error,size_t bytes_transferred);

  tcp::socket socket_;
  enum { max_length = 1024 };
  char data_[max_length];
};


/// Structure to hold information about a single query.
struct queryResult
{
  float score;
  uint32_t docID;
  string url;


  template <typename Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & score;
    ar & docID;
    ar & url;
  }
};

/// Structure to hold information about a single query.
struct query
{
  std::string queryContent;
  int queryNumber;
  template <typename Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & queryContent;
    ar & queryNumber;
  }
};


/// Structure to hold information about a single query and with its answers.
struct queryResults
{
  std::string queryContent;
  int queryNumber;
  vector<queryResult> results;

  template <typename Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & queryContent;
    ar & queryNumber;
    ar & results;
  }
};


#endif /* TCP_CONNECTION_H_ */
